<template>
  <div>
    微信授权
    <div>微信URL:{{winUrl}}</div>
    <div>微信CODE:{{code}}</div>
    <div>RESDATA:{{res}}</div>
  </div>
</template>

<script>
/**
 * 微信网页授权
 */
import { wechatAuthorize } from '@/api'
export default {
  name: 'Auth',
  data () {
    return {
      code: '',
      res: '',
      params: {},
      winUrl: ''
    }
  },
  created () {
    console.log('=============location.search')
    console.log(location.search)
    console.log('=============location.search')
    this.params = this.getUrlCode()
    // 如果连接中有微信返回的 code，则用此 code 调用后端接口，向微信服务器请求用户信息
    // 如果不是从微信重定向过来的，没有带着微信的 code，则直接进入首页
    if (this.params.code) {
      this.code = this.params.code
      wechatAuthorize(this.params.code)
        .then(res => {
          let data = res.data
          console.log(data)
          this.res = JSON.stringify(data)
          localStorage.setItem('wxUserInfo', JSON.stringify(data))
          // this.returnOriginUrl()
        })
        .catch(err => {
          console.log(err)
        })
    } else {
      // this.$router.replace('/')
    }
  },
  methods: {
    returnOriginUrl () {
      let redirectUrl = sessionStorage.getItem('wxRedirectUrl')
      this.$router.replace(redirectUrl)
    },
    getUrlCode () {
      const url = location.search
      // '?code=0113eRlQ0YMwF32af3lQ0BaGlQ03eRls&state=STATE' //
      this.winUrl = url
      let theRequest = {}
      if (url.indexOf('?') !== -1) {
        var str = url.substr(1)
        var strs = str.split('&')
        console.log(strs)
        for (var i = 0; i < strs.length; i++) {
          theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1]
        }
      }
      console.log(theRequest)
      return theRequest
    }
  }
}
</script>
